// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// N [author] rhyme_lph
// E [email]  rhymelph@gmail.com
// O [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/account_entity.dart';
import 'package:finance_app/src/entities/reconciliation_item_entity.dart';
import 'package:finance_app/src/http_service/http_account_service.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/page/all_reports/bank_reconciliation/views/view_report_view.dart';

class ViewReportProvider extends BaseProvider<List<AccountEntity>> {
  AccountEntity currentAccount;
  List<ReconciliationItemEntity> reconciliationList;

  @override
  Future get dataFuture => HttpAccountService.accountList();

  void onSelectAccount(AccountEntity value) {
    obtainContext?.call((context) {
      FocusScope.of(context).requestFocus(FocusNode());
    });
    if (currentAccount != value) {
      currentAccount = value;
      update();
      post(HttpAccountService.getBankReconciliations(currentAccount.id),
          autoHandler: AutoHandler.Toast,
          loadingTip: S.current.loading, onSuccess: (result) {
        reconciliationList =
            getEntityFromResult<List<ReconciliationItemEntity>>(result);
        update();
      });
    }
  }

  void onNavViewReport(ReconciliationItemEntity value) {
    Routes.navigateTo(RouterGenProviders.dateReportPage, params: {
      'type': 76,
      'meta': {
        'bankName': currentAccount.bankName,
        'closingDate': value.endDate,
        'id': value.id,
      }
    });
  }

  void onRefreshReport() async {
    post(dataFuture, autoHandler: AutoHandler.Toast, onSuccess: (result) {
      data = getEntityFromResult<List<AccountEntity>>(result);
      if (currentAccount != null) {
        currentAccount = data.firstWhere(
            (element) => element.id == currentAccount.id,
            orElse: () => currentAccount);
      }
    });
    if (currentAccount != null) {
      post(HttpAccountService.getBankReconciliations(currentAccount.id),
          autoHandler: AutoHandler.Toast,
          loadingTip: S.current.loading, onSuccess: (result) {
        reconciliationList =
            getEntityFromResult<List<ReconciliationItemEntity>>(result);
        update();
      });
    }
  }
}
